package com.iaiai.imail.activity;

import java.io.File;
import java.util.List;
import java.util.TimerTask;

import javax.mail.Message;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.iaiai.imail.core.Attribute;
import com.iaiai.imail.core.IActivity;
import com.iaiai.imail.core.IServiceFactory;
import com.iaiai.imail.entity.Email;
import com.iaiai.imail.entity.Inbox;
import com.iaiai.imail.helper.mail.MailMessage;
import com.iaiai.imail.helper.mail.MailReceiver;
import com.iaiai.imail.helper.mail.MailReceiverInfo;
import com.iaiai.imail.util.DateUtil;

/**
 * 
 * <p>
 * Title: EmailActivity.java
 * </p>
 * <p>
 * E-Mail: 176291935@qq.com
 * </p>
 * <p>
 * QQ: 176291935
 * </p>
 * <p>
 * Http: iaiai.iteye.com
 * </p>
 * <p>
 * Create time: 2012-9-15 下午2:15:28
 * </p>
 * 
 * @author 丸子
 * @version 0.0.1
 */
public class EmailActivity extends IActivity {

	private ListView listView;
	
	private List<Inbox> list;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.email);

		setTitleLayout(); // 设置头

		setTitleText(getBundle().getString("account"));

		listView = (ListView) findViewById(R.id.listView);

		dialog.show();

		execHandle(new Handler() {
			@Override
			public void query() {
				readData();
			}
		}, new Runnable() {
			@Override
			public void run() {
				dialog.dismiss();
				
				listView.setAdapter(new BaseAdapter() {
					@Override
					public int getCount() {
						return list.size();
					}

					@Override
					public Object getItem(int position) {
						return list.get(position);
					}

					@Override
					public long getItemId(int position) {
						return list.get(position).getId().longValue();
					}

					@Override
					public View getView(int position, View convertView, ViewGroup parent) {
						convertView = LayoutInflater.from(EmailActivity.this).inflate(R.layout.inbox_list_item, null);
						TextView title = (TextView) convertView.findViewById(R.id.title);
						title.setText(list.get(position).getTitle());
						TextView info = (TextView) convertView.findViewById(R.id.info);
						info.setText(list.get(position).getSendDate());
						return convertView;
					}
				});
			}
		});
	}

	/**
	 * 设置头
	 */
	private void setTitleLayout() {
		// 显示返回按钮
		insertTitleLayoutButton(R.drawable.icon_return, new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent activity = new Intent(EmailActivity.this, MainActivity.class);
				startActivity(activity);
				finish();
				overridePendingTransition(R.anim.push_right_out, R.anim.push_right_in);
			}
		});
	}

	private void readData() {
		final Email email = IServiceFactory.getInstance().getEmailDao().queryEmail(getBundle().getString("account"));
		list = IServiceFactory.getInstance().getInboxDao().queryInboxByEmail(email.getId());

		// 收信，创建另一线程获得短信
		execHandle(new TimerTask() {
			@Override
			public void run() {
				testEmail(email);
			}
		}, 0l);
	}

	/**
	 * 收邮件
	 */
	private void testEmail(Email email) {
		new File(Attribute.getSdCard() + "/imail").mkdirs();

		MailReceiverInfo receiverInfo = new MailReceiverInfo();
		receiverInfo.setMailServerHost(email.getServiceAddress());
		receiverInfo.setMailServerPort(email.getServicePort().toString());
		receiverInfo.setValidate(true);
		receiverInfo.setUserName(email.getUserName());
		receiverInfo.setPassword(email.getPassword());
		receiverInfo.setAttachmentDir(Attribute.getSdCard() + "/imail");
		receiverInfo.setEmailDir(Attribute.getSdCard() + "/imail");

		MailReceiver receiver = new MailReceiver(receiverInfo);
		try {
			receiver.receiveAllMail();
			Message[] ms = receiver.getMessages();

			if (ms != null) {
				for (int i = 0; i < ms.length; i++) {
					String mid = MailMessage.getMessageId(ms[i]);
					
					//判断是否以经接收过此邮件
//					if(IServiceFactory.getInstance().getInboxDao().isMessage(mid)){
//						continue;
//					}
					
					//添加到数据库中
					Inbox inbox = new Inbox();
					inbox.setEid(email.getId());
					inbox.setMid(mid);
					inbox.setTitle(MailMessage.getSubject(ms[i]));
					inbox.setContent(MailMessage.getBodyContent(ms[i]));
					inbox.setForm(MailMessage.getFrom(ms[i]));
					inbox.setToAddress(MailMessage.getTOAddress(ms[i]));
					inbox.setCc(MailMessage.getCCAddress(ms[i]));
					inbox.setBcc(MailMessage.getBCCAddress(ms[i]));
					inbox.setSendDate(DateUtil.formatDateYMDHMS(MailMessage.getSentDate(ms[i])));
					inbox.setReplysign(MailMessage.getReplySign(ms[i])?1:0);
					inbox.setAttach(MailMessage.isContainAttach(ms[i])?1:0);
					inbox.setContentType(MailMessage.getContentType(ms[i]));
					inbox.setDisposition(MailMessage.getDisposition(ms[i]));
					inbox.setDescription(MailMessage.getDescription(ms[i]));
					inbox.setSize(MailMessage.getSize(ms[i]));
					inbox.setHeader(null);
					inbox.setCreateDate(DateUtil.getDateTime());
					inbox.setRead(0);	//未读
					
					IServiceFactory.getInstance().getInboxDao().insertInbox(inbox);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//修改接收次数
		email.setRcount(email.getRcount().intValue()+1);
		IServiceFactory.getInstance().getEmailDao().updateEmail(email);
	}

}
